
# -*- coding: utf-8 -*-

import os
import cv2
from peewee import *
from models.Base import BaseModel
from models.User import User
from config.Config import IMAGE_DIR, RAW_IMAGE_DIR
from util.FacialRecognition import detect_faces, to_grayscale, crop_faces

class Image(BaseModel):

	path = CharField()
	user = ForeignKeyField(User)

	def persist(self, cv_image, photonumber):
		try:
			path = unicode(os.path.join(IMAGE_DIR, unicode(self.user.username)))
			rawpath = unicode(os.path.join(RAW_IMAGE_DIR, unicode(self.user.username)))
			faces = detect_faces(cv_image)
			if len(faces) > 0:
				path += "/%s.jpg" % str(photonumber)
				rawpath += "/%s.jpg" % str(photonumber)
				path = unicode(os.path.abspath(path))
				rawpath = unicode(os.path.abspath(rawpath))
				cropped = to_grayscale(crop_faces(cv_image, faces))
				cv2.imwrite(path, cropped)
				cv2.imwrite(rawpath, cv_image)
				self.path = path
				self.save()
				return "success"
		except:
			pass
		return "failure"
